package com.example.securitytest.service.impl;

import com.example.securitytest.domain.LoginUser;
import com.example.securitytest.domain.ResponseResult;
import com.example.securitytest.domain.User;
import com.example.securitytest.service.LoginService;
import com.example.securitytest.utils.JwtUtil;
import com.example.securitytest.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.HashMap;
import java.util.Objects;



@Service
public class LoginServiceImpl implements LoginService {
	private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

	@Autowired
	private AuthenticationManager authenticationManager;
		@Autowired
		private RedisCache redisCache;
		@Override
		public ResponseResult login(User user, String userAgent) {

			//AuthenticationManager authenticate进行用户认证
			UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
			Authentication authenticate = authenticationManager.authenticate(authenticationToken);

			//如果认证没通过，给出对应的提示
			if(Objects.isNull(authenticate)){
				throw new RuntimeException("用户名或密码错误");
			}

	        //使用userid生成token
			LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
			String userId = loginUser.getUser().getId().toString();
			String username = loginUser.getUser().getUsername();
			String jwt = JwtUtil.createJWT(userId);

	        //authenticate存入redis
			redisCache.setCacheObject("login:"+userId,loginUser);

	        //把token响应给前端 如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
			HashMap<String,String> map = new HashMap<>();
			map.put("token",jwt);

			// 记录日志
			logger.info("User {} logged in with browser: {}", username, userAgent);

			return new ResponseResult(200,"登陆成功",map);


		}

	@Override
	public ResponseResult logout() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		int userid = loginUser.getUser().getId();
		redisCache.deleteObject("login:"+userid);
		return new ResponseResult(200,"退出成功");
	}

}


